<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>并发请求</title>
</head>

<body>
    <button id="btn">发起请求</button>
    <script>
        function ajax(url) {
            return new Promise((resolve) => {
                const xhr = new XMLHttpRequest()
                xhr.open('get', url, true)
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200 || xhr.status === 304) {
                            resolve(xhr.responseText)
                        }
                    }
                }
                xhr.send()
            })
        }
   
    function handleRequest(max, urls) {
        return new Promise((resolve) => {
            if (urls.length === 0) {
                resolve([]);
                return;
            }
            const result = [];
            let index = 0;

            async function request() {
                if (index >= urls.length) {
                    return;
                }
                const i = index;
                const url = urls[index];
                index++;
                try {
                    const res = await ajax(url);
                    result[i] = res;
                } catch (error) {
                    result[i] = error;
                } finally {
                    // 这个是 相当于 当前的这个通道完成后在继续 调用下一个接口
                    request();
                }
            }
            // 这个是请求的并发数和url数量选最小的
            const times = Math.min(max, urls.length);
            for (let i = 0; i < times; i++) {
                request();
            }

            resolve(result);
        });
    }


        const urls = []
        for (let i = 0; i < 100; i++) {
            urls.push('http://localhost:3000/getData')
        }
        const btn = document.getElementById('btn')
        btn.addEventListener('click', () => {
            handleRequest(5, urls).then(res => {
                console.log(res);
            })
        })

    </script>
</body>

</html>